//
//  MTStoreViewController.m
//  ebook
//
//  Created by 吴超飞 on 16/1/14.
//  Copyright © 2016年 Moton. All rights reserved.
//

#import "MTStoreViewController.h"
#import "EbookNetRequest.h"
#import "SearachViewController.h"
#import "MTNavigationController.h"
#import "MTTabBarController.h"

@interface MTStoreViewController () <StoreMenuViewDelegate, UIScrollViewDelegate,UITabBarControllerDelegate>{
    int menuRetryCount;//递归请求menu数据的重试次数
}

@property (nonatomic, retain) NSArray *menuUrlArray;
@property (nonatomic, strong) NSMutableArray *wkwebviewArray;
@property (nonatomic, strong) NSMutableArray *bridgeArray;
@property (nonatomic, strong) NSMutableArray *progressArray;
@property (nonatomic, retain) NSString *urlKey;
@property (nonatomic, retain) UIView  *lockView;
@property (nonatomic, retain) NSString *titleName;

@end

@implementation MTStoreViewController

-(instancetype)initWithTitle:(NSString *)title tabTitle:(NSString *)tabTitle urlKey:(NSString *)urlKey{
    if (self = [super init]) {
        self.titleName = title;
        self.tabBarItem.title = tabTitle;
        self.urlKey = urlKey;
    }
    return self;
}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    self.title = self.titleName;
    menuRetryCount = 0;
    self.view.backgroundColor = MTConfigColor(@"MTBookCity_Bg_Color");
    
    [self.view addSubview:self.scrollView];
    [self setBarItem];
    self.tabBarController.delegate = self;
//    [self infoRate]; //关闭评论
}

-(void)viewDidAppear:(BOOL)animated{
    
    [super viewDidAppear:animated];
    [self showMenu];
}

//提示用户评论
-(void)infoRate{
    //书库：menustore;   精选：store
    if ([self.urlKey isEqualToString:@"menustore"]&&![[NSUserDefaults standardUserDefaults] boolForKey:kIsUnLock]) {//对于没有解锁的用户，书库锁定提示用户评论
        //接口启用评论功能，用户启动超过一次，且该版本没有评论过，提示用户评分
        int openrate = [[[NSKeyedUnarchiver unarchiveObjectWithData:[[NSUserDefaults standardUserDefaults] objectForKey:KBookCityData]] objectForKey:@"openrate"] intValue];
        NSInteger thisTime = [[[NSUserDefaults standardUserDefaults] objectForKey:kLauchTimes] integerValue]+1;
        [[NSUserDefaults standardUserDefaults] setObject:@(thisTime) forKey:kLauchTimes];
        [[NSUserDefaults standardUserDefaults] synchronize];
        if(openrate>0 && thisTime > 1)
            [self.view addSubview:self.lockView];
    }else{
        [self.lockView removeFromSuperview];
    }
}

//（超过20分钟）后台运行进入前台时并不会执行viewDidAppear，防止白屏，自动刷新菜单
-(void)enterForegroundReloadWebview{
    [self reloadSelectedMenu:-1];
}

-(void)showMenu{
    
    id data = [[NSUserDefaults standardUserDefaults] objectForKey:KBookCityData];
    NSDictionary *dict = [NSKeyedUnarchiver unarchiveObjectWithData:data];
    NSArray *menuArray = dict[@"data"][self.urlKey];
    
    if (!menuArray) {//没有获取到基础数据则网络请求获取
        __weak typeof(self) weakSelf = self;
        BOOL islogin = [[NSUserDefaults standardUserDefaults] boolForKey:kIsLogin];
        if(islogin){
            [EbookNetRequest getStoreMenuSuccess:^(int stateCode, NSString *successMsg, NSDictionary *dict) {
                __strong __typeof(self) strongSelf = weakSelf;
                [[NSUserDefaults standardUserDefaults] setObject:[NSKeyedArchiver archivedDataWithRootObject:dict] forKey:KBookCityData];
                [[NSUserDefaults standardUserDefaults] synchronize];
                if(menuRetryCount++<3)//最多重试三次
                    [strongSelf showMenu];
            } failed:^(int stateCode, NSString *failMsg) {
                
            }];
        }else{
            [GuestLoginManager autoLogin:^(BOOL issuc) {
                if(issuc)
                    [EbookNetRequest getStoreMenuSuccess:^(int stateCode, NSString *successMsg, NSDictionary *dict) {
                        __strong __typeof(self) strongSelf = weakSelf;
                        [[NSUserDefaults standardUserDefaults] setObject:[NSKeyedArchiver archivedDataWithRootObject:dict] forKey:KBookCityData];
                        [[NSUserDefaults standardUserDefaults] synchronize];
                        if(menuRetryCount++<3)//最多重试三次
                            [strongSelf showMenu];
                    } failed:^(int stateCode, NSString *failMsg) {
                        
                    }];
            }];
        }
        return;
    }
    
    if (!_menuView) {
        _menuView = [[StoreMenuView alloc] initWithFrame:CGRectMake(0, 0, MTScreenW, 44) withMenuArray:menuArray];
        _menuView.delegate = self;
        
        [self.view addSubview:self.menuView];
        self.webView.frame = CGRectMake(0, CGRectGetMaxY(self.menuView.frame), MTScreenW, MTScreenH - SafeAreaBTabbarHeight - CGRectGetMaxY(self.menuView.frame) - SafeAreaTopHeight);
        
        self.menuUrlArray = [[NSArray alloc] initWithArray:[self getBookCityData]];
        self.scrollView.contentSize = CGSizeMake(MTScreenW*self.menuUrlArray.count,0);
        [self fillViewWitData];
    }
}

//重写父类的方法，刷新界面
- (void)reloadView
{
    [self showMenu];
    [self hiddenFailView];
    [self reloadSelectedMenu:_menuView.selectedIndex];
}

//刷新指定菜单，index<0时刷新所有
-(void)reloadSelectedMenu:(NSInteger)index{
    
    for (UIView *view in _scrollView.subviews) {
        if( [view isKindOfClass:[WKWebView class]]){
            
            WKWebView *webview = (WKWebView*)view;
            if(index<0||webview.tag == _menuView.selectedIndex+100)
                [self webView:webview loadUrl:[_menuView originalUrlOfMenu:view.tag-100]];
        }else if( [view isKindOfClass:[UIWebView class]]){
            
            UIWebView *webview = (UIWebView*)view;
            if(index<0||webview.tag == _menuView.selectedIndex+100)
                [self webView:webview loadUrl:[_menuView originalUrlOfMenu:view.tag-100]];
        }
    }
}

-(void)setBarItem{
    
    UIBarButtonItem *homeBarBtn = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"home_icon"] style:UIBarButtonItemStylePlain target:self action:@selector(homeBtnClick:)];
    homeBarBtn.tintColor = MTConfigColor(@"MTNavigationBar_leftItem_Color");
    self.navigationItem.leftBarButtonItem = homeBarBtn;
    
    UIBarButtonItem *searchItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSearch target:self action:@selector(searchBook:)];
    searchItem.tintColor = MTConfigColor(@"MTNavigationBar_rightItem_Color");
    self.navigationItem.rightBarButtonItem = searchItem;
}

#pragma mark - searchBook
- (void)searchBook:(id)sender
{
    self.navigationItem.rightBarButtonItem.enabled = NO;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        self.navigationItem.rightBarButtonItem.enabled = YES;
    });
    
    SearachViewController *searchVc = [[SearachViewController alloc] init];
    [self.navigationController pushViewController:searchVc animated:YES];
}

-(void)homeBtnClick:(UIBarButtonItem *)item{
    
    [_menuView setSelectedButtonIndex:0];
}

- (NSArray *)getBookCityData
{
    NSMutableArray *arr = [NSMutableArray array];
    id data = [[NSUserDefaults standardUserDefaults] objectForKey:KBookCityData];
    NSDictionary *dict= [NSKeyedUnarchiver unarchiveObjectWithData:data];
    NSArray *menu = dict[@"data"][self.urlKey];
    [menu enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        StoreMenu *sm = [[StoreMenu alloc] initWithDictionary:obj];
        // [arr addObject:@"http://192.168.0.113"];//sm.url];
        [arr addObject:sm.url];
    }];
    return [NSArray arrayWithArray:arr];
}

- (void)fillViewWitData
{
    __weak typeof(self) weakSelf = self;
    _progressArray = nil;
    _bridgeArray = nil;
    _wkwebviewArray = nil;
    [_menuUrlArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        __strong __typeof(self) strongSelf = weakSelf;
        CGRect frame = CGRectMake(idx*MTScreenW, CGRectGetMinY(strongSelf.webView.frame), MTScreenW, CGRectGetHeight(strongSelf.webView.frame));
        
        UIView *view;
        if (!_bridgeArray)_bridgeArray = [NSMutableArray array];
        if (iOS8) {
            if(!_progressArray)_progressArray = [NSMutableArray array];
            if(!_wkwebviewArray)_wkwebviewArray = [NSMutableArray array];
            
            WKWebView *webview = [[WKWebView alloc] initWithFrame:frame];
            webview.scrollView.bounces = NO;
            webview.navigationDelegate = self;
            webview.UIDelegate = self;
            webview.scrollView.scrollsToTop = idx==0;
            view = webview;
            
            WKWebViewJavascriptBridge *bridge = [WKWebViewJavascriptBridge bridgeForWebView:webview webViewDelegate:strongSelf handler:strongSelf.messageHandler] ;
            
            [_bridgeArray addObject:bridge];
            [_wkwebviewArray addObject:webview];
            
            UIProgressView *progressView = [self createProgressView];
            [webview addSubview:progressView];
            [_progressArray addObject:progressView];
            [webview addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
            
        }else{
            
            UIWebView *webview = [[UIWebView alloc] initWithFrame:frame];
            webview.scrollView.bounces = NO;
            webview.delegate = self;
            webview.scalesPageToFit = YES;
            webview.scrollView.scrollsToTop = idx==0;
            WebViewJavascriptBridge *bridge = [WebViewJavascriptBridge bridgeForWebView:webview webViewDelegate:strongSelf handler:strongSelf.messageHandler];
            [_bridgeArray addObject:bridge];
            view = webview;
        }
        view.tag = idx+100;
        view.backgroundColor = [UIColor whiteColor];
        
        [strongSelf webView:view loadUrl:_menuUrlArray[idx]];
        [strongSelf.scrollView addSubview:view];
        
    }];
}

// 计算wkWebView进度条
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    
    if ([object isKindOfClass:[WKWebView class]] && [keyPath isEqualToString:@"estimatedProgress"]) {
        
        WKWebView *wkWebview = (WKWebView *)object;
        NSInteger index = wkWebview.tag-100;
        
        if(index<5){
            UIProgressView *progressView = [_progressArray objectAtIndex:index];
            CGFloat newprogress = [[change objectForKey:NSKeyValueChangeNewKey] doubleValue];
            if (newprogress == 1) {
                progressView.hidden = YES;
                [progressView setProgress:0 animated:NO];
            }else {
                progressView.hidden = NO;
                [progressView setProgress:newprogress animated:YES];
            }
        }
    }
}

-(UIView *)lockView{
    if(!_lockView){
        float y = kMenuHeight;
        _lockView = [[UIView alloc] initWithFrame:CGRectMake(0, y, MTScreenW, CGRectGetHeight(self.scrollView.frame)-y)];
        _lockView.backgroundColor = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.3];
        
        UIImageView *lockImgview = [[UIImageView alloc] initWithFrame:CGRectMake(0, 100, 120, 120)];
        lockImgview.image = [UIImage imageNamed:@"lock"];
        lockImgview.centerX = _lockView.centerX;
        [_lockView addSubview:lockImgview];
        
        NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:@"点击前往五星好评解锁书库"];
        NSRange strRange = {0,[str length]};
        [str addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:strRange];
        [str addAttribute:NSForegroundColorAttributeName value:[UIColor whiteColor] range:strRange];
        UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(0, 250, 280, 40)];
        [btn setAttributedTitle:str forState:UIControlStateNormal];
        btn.centerX = _lockView.centerX;
        [btn addTarget:self action:@selector(toStoreRate) forControlEvents:UIControlEventTouchUpInside];
        [_lockView addSubview:btn];
    }
    
    return _lockView;
}

-(void)toStoreRate{
    NSString *str = [NSString stringWithFormat: @"itms-apps://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?type=Purple+Software&id=%@&pageNumber=0&sortOrdering=2&mt=8", kAppidInAppstore];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
    [BookcaseOprationController unlock:^(int stateCode, NSString *successMsg, NSDictionary *dict) {
        [self.lockView removeFromSuperview];
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:kIsUnLock];
        [[NSUserDefaults standardUserDefaults] synchronize];
    } failed:^(int stateCode, NSString *failMsg) {
        
    }];
}

- (UIScrollView *)scrollView
{
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc] init];
        _scrollView.frame = CGRectMake(0, 0, MTScreenW, MTScreenH-SafeAreaTopHeight-SafeAreaBTabbarHeight);
        _scrollView.contentOffset = CGPointMake(0, 0);
        _scrollView.showsHorizontalScrollIndicator = NO;
        _scrollView.pagingEnabled = YES;
        _scrollView.delegate = self;
        _scrollView.bounces = NO;
        _scrollView.showsHorizontalScrollIndicator = NO;
        _scrollView.scrollsToTop = NO;
    }
    return _scrollView;
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    
    if(scrollView == _scrollView){
        
        CGPoint offset = scrollView.contentOffset;
        NSInteger currentPage = offset.x / MTScreenW;
        
        [_scrollView setContentOffset:scrollView.contentOffset animated:YES];
        [self redirectMenu:currentPage];
    }
}

#pragma mark - UITabBarControllerDelegate 点击当前tabbar刷新当前选中菜单项
- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController
{
    //判断当前点击的是否是书城VC，如果跟上次点击相同，则需要刷新当前菜单
    if(((AppDelegate*)[UIApplication sharedApplication].delegate).lastSelectedTabbarIndex==tabBarController.selectedIndex){
        if([viewController isKindOfClass:[MTNavigationController class]]){
            UIViewController *topVc = (((UINavigationController*)viewController).topViewController);
            if ([topVc isKindOfClass:[MTStoreViewController class]]) {
                MTStoreViewController *selectedVc = (MTStoreViewController*)topVc;                StoreMenuView *cmenuview = selectedVc.menuView;
                UIView *view = [selectedVc.scrollView viewWithTag:100+cmenuview.selectedIndex];
                [self webView:view loadUrl:cmenuview.currentMenu.url];
            }
        }
    }
    ((AppDelegate*)[UIApplication sharedApplication].delegate).lastSelectedTabbarIndex=tabBarController.selectedIndex;
}

#pragma mark - StoreMenuViewDelegate 菜单点击事件
-(void)storeMenuView:(StoreMenuView *)view didSelected:(StoreMenu *)menu{
    
    for (int i = 0; i < _menuUrlArray.count; i++) {
        
        if ([menu.url isEqualToString:_menuUrlArray[i]]) {
            
            [_scrollView setContentOffset:CGPointMake(i*MTScreenW, 0) animated:YES];
            
            for (UIView *view in _scrollView.subviews) {
                
                if([view isKindOfClass:[WKWebView class]]){
                    WKWebView *webview = (WKWebView*)view;
                    webview.scrollView.scrollsToTop = NO;
                }else if ([view isKindOfClass:[UIWebView class]]){
                    UIWebView *webview = (UIWebView*)view;
                    webview.scrollView.scrollsToTop = NO;
                }
                
                if( ([view isKindOfClass:[WKWebView class]]||[view isKindOfClass:[UIWebView class]]) && (view.tag - 100 == i)){
                    
                    NSString *script = @"document.documentElement.innerHTML";//空白时，获取到的内容为"<head></head><body></body>"
                    if([view isKindOfClass:[WKWebView class]]){
                        WKWebView *webview = (WKWebView*)view;
                        webview.scrollView.scrollsToTop = YES;
                        [webview evaluateJavaScript:script completionHandler:^(NSString *content, NSError * _Nullable error) {
                            if (content.length<100||_menuView.lastSelectedIndex==_menuView.selectedIndex) {
                                [self webView:webview loadUrl:menu.url];
                            }
                        }];
                        for(int j= 0;j<5;j++)[webview goBack];
                    }else if ([view isKindOfClass:[UIWebView class]]){
                        UIWebView *webview = (UIWebView*)view;
                        webview.scrollView.scrollsToTop = YES;
                        NSString *html = [webview stringByEvaluatingJavaScriptFromString:script];
                        if (html.length<100||_menuView.lastSelectedIndex==_menuView.selectedIndex) {//空白页或者点击当前页刷新
                            [self webView:webview loadUrl:menu.url];
                        }
                        for(int j= 0;j<5;j++)[webview goBack];
                    }
                }
            }
            
            break;
        }
    }
}

//重写父类方法实现菜单选择,由原来的只移动菜单不做事件处理改为直接模拟事件处理
-(void)redirectMenu:(NSInteger)index{
    
    [_menuView performClickBtn:index];
}

-(void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    if(iOS8){
        for(WKWebView *wk in _progressArray){
            [wk removeObserver:self forKeyPath:@"estimatedProgress"];
        }
    }
}

@end
